{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "17f894b5",
   "metadata": {
    "nbsphinx": "hidden"
   },
   "outputs": [],
   "source": [
    "import warnings\n",
    "\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "import pandas as pd\n",
    "\n",
    "import featuretools as ft\n",
    "from featuretools.demo.weather import load_weather\n",
    "from featuretools.primitives import Lag, RollingMean, RollingMin"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a8104f18",
   "metadata": {},
   "source": [
    "# Feature Engineering for Time Series Problems"
   ]
  },
  {
   "cell_type": "raw",
   "id": "9cd9cb82",
   "metadata": {
    "raw_mimetype": "text/restructuredtext"
   },
   "source": [
    ".. note::\n",
    "        This guide focuses on feature engineering for single-table time series problems; it does not cover how to handle temporal multi-table data for other machine learning problem types. A more general guide on handling time in Featuretools can be found `here <../getting_started/handling_time.ipynb>`_."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0cf3cebc",
   "metadata": {},
   "source": [
    "Time series forecasting consists of predicting future values of a target using earlier observations. In datasets that are used in time series problems, there is an inherent temporal ordering to the data (determined by a time index), and  the sequential target values we're predicting are highly dependent on one another. Feature engineering for time series problems exploits the fact that more recent observations are more predictive than more distant ones.\n",
    "\n",
    "This guide will explore how to use Featuretools for automating feature engineering for univariate time series problems, or problems in which only the time index and target column are included.\n",
    " \n",
    "We'll be working with a temperature demo EntitySet that contains one DataFrame, `temperatures`. The `temperatures` dataframe contains the minimum daily temperatures that we will be predicting. In total, it has three columns: `id`, `Temp`, and `Date`. The `id` column is the index that is necessary for Featuretools' purposes. The other two are important for univariate time series problems: `Date` is our time index, and `Temp` is our target column. The engineered features will be built from these two columns."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "862e46da",
   "metadata": {},
   "outputs": [],
   "source": [
    "es = load_weather()\n",
    "\n",
    "es[\"temperatures\"].head(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "90242e31",
   "metadata": {},
   "outputs": [],
   "source": [
    "es[\"temperatures\"][\"Temp\"].plot(ylabel=\"Temp (C)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "060eb035",
   "metadata": {},
   "source": [
    "## Understanding The Feature Engineering Window\n",
    "\n",
    "In multi-table datasets, a feature engineering window for a single row in the target DataFrame extends forward in time over observations in child DataFrames starting at the time index and ending when either the cutoff time or last time index is reached. \n",
    "\n",
    "![Multi Table Timeline](../_static/images/multi_table_FE_timeline.png)\n",
    "\n",
    "In single-table time series datasets, the feature engineering window for a single value extends backwards in time within the same column. Because of this, the concepts of cutoff time and last time index are not relevant in the same way.\n",
    "\n",
    "For example: The cutoff time for a single-table time series dataset would create the training and test data split. During DFS, features would not be calculated after the cutoff time. This same behavior can often times be achieved more simply by splitting the data prior to creating the EntitySet, since filtering the data at feature matrix calculation is more computationally intensive than splitting the data ahead of time.\n",
    "\n",
    "```\n",
    "split_point = int(df.shape[0]*.7)\n",
    "\n",
    "training_data = df[:split_point]\n",
    "test_data = df[split_point:]\n",
    "```\n",
    "\n",
    "So, since we can't use the existing parameters for defining each observation's feature engineering window, we'll need to define new the concepts of `gap` and `window_length`. These will allow us to set a feature engineering window that exists prior to each observation.\n",
    "\n",
    "## Gap and Window Length\n",
    "\n",
    "Note that we will be using integers when defining the gap and window length. This implies that our data occurs at evenly spaced intervals--in this case daily--so a number `n` corresponds to `n` days. Support for unevenly spaced intervals is ongoing and can be explored with the Woodwork method [df.ww.infer_temporal_frequencies](https://woodwork.alteryx.com/en/stable/generated/woodwork.table_accessor.WoodworkTableAccessor.infer_temporal_frequencies.html#woodwork.table_accessor.WoodworkTableAccessor.infer_temporal_frequencies).\n",
    "\n",
    "If we are at a point in time `t`, we have access to information from times less than `t` (past values), and we do not have information from times greater than `t` (future values). Our limitations in feature engineering, then, will come from when exactly before `t` we have access to the data. \n",
    "\n",
    "Consider an example where we're recording data that takes a week to ingest; the earliest data we have access to is from seven days ago, or `t - 7`. We'll call this our `gap`. A `gap` of 0 would include the instance itself, which we must be careful to avoid in time series problems, as this exposes our target.\n",
    "\n",
    "We also need to determine how far back in time before `t - 7` we can go. Too far back, and we may lose the potency of our recent observations, but too recent, and we may not capture the full spectrum of behaviors displayed by the data. In this example, let's say that we only want to look at 5 days worth of data at a time. We'll call this our `window_length`. \n",
    "\n",
    "![Time Series Timeline](../_static/images/time_series_FE_timeline.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a90799f1",
   "metadata": {},
   "outputs": [],
   "source": [
    "gap = 7\n",
    "window_length = 5"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "460b4c49",
   "metadata": {},
   "source": [
    "With these two parameters (`gap` and `window_length`) set, we have defined our feature engineering window. Now, we can move onto defining our feature primitives.\n",
    "\n",
    "## Time Series Primitives\n",
    "\n",
    "There are three types of primitives we'll focus on for time series problems. One of them will extract features from the time index, and the other two types will extract features from our target column. \n",
    "\n",
    "### Datetime Transform Primitives\n",
    "\n",
    "We need a way of implicating time in our time series features. Yes, using recent temperatures is incredibly predictive in determining future temperatures, but there is also a whole host of historical data suggesting that the month of the year is a pretty good indicator for the temperature outside. However, if we look at the data, we'll see that, though the day changes, the observations are always taken at the same hour, so the `Hour` primitive will not likely be useful. Of course, in a dataset that is measured at an hourly frequency or one more granular, `Hour` may be incrediby predictive. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "65246092",
   "metadata": {},
   "outputs": [],
   "source": [
    "datetime_primitives = [\"Day\", \"Year\", \"Weekday\", \"Month\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "95d8c86a",
   "metadata": {},
   "source": [
    "The full list of datetime transform primitives can be seen [here](https://featuretools.alteryx.com/en/latest/api_reference.html#datetime-transform-primitives).\n",
    "\n",
    "### Delaying Primitives\n",
    "\n",
    "The simplest thing we can do with our target column is to build features that are delayed (or lagging) versions of the target column. We'll make one feature per observation in our feature engineering windows, so we'll range over time from `t - gap - window_length` to `t - gap`. \n",
    "\n",
    "For this purpose, we can use our `Lag` primitive and create one primitive for each instance in our window. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b9e1fa8f",
   "metadata": {},
   "outputs": [],
   "source": [
    "delaying_primitives = [Lag(periods=i + gap) for i in range(window_length)]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "03cd4474",
   "metadata": {},
   "source": [
    "### Rolling Transform Primitives\n",
    "\n",
    "Since we have access to the entire feature engineering window, we can aggregate over that window. Featuretools has several rolling primitives with which we can achieve this. Here, we'll use the `RollingMean` and `RollingMin` primitives, setting the `gap` and `window_length` accordingly. Here, the gap is incredibly important, because when the gap is zero, it means the current observation's taret value is present in the window, which exposes our target.\n",
    "\n",
    "This concern also exists for other primitives that reference earlier values in the dataframe. Because of this, when using primitives for time series feature engineering, one must be incredibly careful to not use primitives on the target column that incorporate the current observation when calculating a feature value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ed6cc722",
   "metadata": {},
   "outputs": [],
   "source": [
    "rolling_mean_primitive = RollingMean(\n",
    "    window_length=window_length, gap=gap, min_periods=window_length\n",
    ")\n",
    "\n",
    "rolling_min_primitive = RollingMin(\n",
    "    window_length=window_length, gap=gap, min_periods=window_length\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1eb2a6e1",
   "metadata": {},
   "source": [
    "The full list of rolling transform primitives can be seen [here](https://featuretools.alteryx.com/en/latest/api_reference.html#rolling-transform-primitives).\n",
    "\n",
    "## Run DFS\n",
    "\n",
    "Now that we've definied our time series primitives, we can pass them into DFS and get our feature matrix! \n",
    "\n",
    "Let's take a look at an actual feature engineering window as we defined with `gap` and `window_length` above. Below is an example of how we can extract many features using the same feature engineering window without exposing our target value.\n",
    "\n",
    "![FE Window](../_static/images/window_calculations.png)\n",
    "\n",
    "With the image above, we see how all of our defined primitives get used to create many features from just the two columns we have access to."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "42f52b73",
   "metadata": {},
   "outputs": [],
   "source": [
    "fm, f = ft.dfs(\n",
    "    entityset=es,\n",
    "    target_dataframe_name=\"temperatures\",\n",
    "    trans_primitives=(\n",
    "        datetime_primitives\n",
    "        + delaying_primitives\n",
    "        + [rolling_mean_primitive, rolling_min_primitive]\n",
    "    ),\n",
    "    cutoff_time=pd.Timestamp(\"1987-1-30\"),\n",
    ")\n",
    "\n",
    "f"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9e8ce29d",
   "metadata": {},
   "outputs": [],
   "source": [
    "fm.iloc[:, [0, 2, 6, 7, 8, 9]].head(15)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b984ff57",
   "metadata": {},
   "source": [
    "Above is our time series feature matrix! The rolling and delayed features are built from our target column, but do not expose it. We can now use the feature matrix to create a machine learning model that predicts future minimum daily temperatures."
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Raw Cell Format",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
